package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.Step;
import com.recipedb.recipedb.service.StepService;
import com.recipedb.recipedb.util.MergeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

import static com.recipedb.recipedb.util.MergeUtils.mergeForPut;

@RestController
@RequestMapping("/api/step")
public class StepController {

    @Autowired
    private StepService service;

    @PostMapping
    public Step add(@RequestBody Step entity) {
        return service.save(entity);
    }

    @DeleteMapping
    public void delete(@RequestParam Long id) {
        service.deleteById(id);
    }

    @GetMapping("/single")
    public Optional<Step> get(@RequestParam Long id) {
        return service.findById(id);
    }

    @GetMapping("/all")
    public List<Step> getAll() {
        return service.findAll();
    }

    @PatchMapping("/{id}")
    public ResponseEntity<Step> partialUpdate(@PathVariable Long id, @RequestBody Step entity) {
        Optional<Step> updatedStep = service.partialUpdate(id, entity);
        return updatedStep
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<Step> update(
            @PathVariable Long id,
            @RequestBody Step incoming) {

        Optional<Step> existingOpt = service.findById(id);
        if (existingOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        Step merged = MergeUtils.mergeForPut(existingOpt.get(), incoming);

        Optional<Step> updated = service.partialUpdate(id, merged);
        return updated
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }



    @GetMapping("/recipe/{recipeId}")
    public List<Step> getStepsByRecipeId(@PathVariable Long recipeId) {
        return service.findByRecipeId(recipeId);
    }

    @PostMapping("/{recipeId}/{stepOrder}/image")
    public ResponseEntity<String> uploadImage(
            @PathVariable Long recipeId,
            @PathVariable Integer stepOrder,
            @RequestParam("file") MultipartFile file
    ) throws IOException {

        Step step = service.findByRecipeId(recipeId)
                .stream()
                .filter(s -> s.getStepOrder().equals(stepOrder))
                .findFirst()
                .orElse(null);

        if (step == null) return ResponseEntity.notFound().build();

        String fileName = String.format("R%06d_S%02d.jpg", recipeId, stepOrder);

        // 绝对路径
        String dir = "/var/www/recipe-app/uploads/recipes/steps/";
        File targetDir = new File(dir);
        if (!targetDir.exists()) targetDir.mkdirs();

        File targetFile = new File(targetDir, fileName);
        file.transferTo(targetFile);

        // 数据库存储相对 URL
        String dbPath = "/uploads/recipes/steps/" + fileName;
        service.updateImagePath(step.getId(), dbPath);

        return ResponseEntity.ok(dbPath);
    }


    @DeleteMapping("/{recipeId}/{stepOrder}/image")
    public ResponseEntity<Void> deleteImage(
            @PathVariable Long recipeId,
            @PathVariable Integer stepOrder
    ) {

        List<Step> steps = service.findByRecipeId(recipeId);
        Step step = steps.stream()
                .filter(s -> s.getStepOrder().equals(stepOrder))
                .findFirst()
                .orElse(null);

        if (step == null) return ResponseEntity.notFound().build();

        if (step.getImagePath() != null) {
            // 拼接绝对路径
            String absolutePath = "/var/www/recipe-app" + step.getImagePath();
            File f = new File(absolutePath);
            if (f.exists() && !f.isDirectory()) {
                if (!f.delete()) {
                    System.err.println("Failed to delete file: " + absolutePath);
                }
            }
        }

        service.clearImagePath(step.getId());
        return ResponseEntity.ok().build();
    }


}
